package com.snapan.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 代码生成器工具类
 * 用于根据数据库表结构自动生成SSM框架的代码
 */
public class CodeGenerator {
    
    // 数据库连接信息
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/snapan?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    
    // 项目包路径
    private static final String BASE_PACKAGE = "com.snapan";
    private static final String ENTITY_PACKAGE = BASE_PACKAGE + ".entity";
    private static final String DAO_PACKAGE = BASE_PACKAGE + ".dao";
    private static final String SERVICE_PACKAGE = BASE_PACKAGE + ".service";
    private static final String CONTROLLER_PACKAGE = BASE_PACKAGE + ".controller";
    
    // 项目路径
    private static final String PROJECT_PATH = System.getProperty("user.dir");
    private static final String SRC_PATH = PROJECT_PATH + "/src/main/java";
    
    /**
     * 生成指定表的代码
     */
    public static void generateCode(String tableName) {
        try {
            // 获取表信息
            TableInfo tableInfo = getTableInfo(tableName);
            if (tableInfo == null) {
                System.out.println("表 " + tableName + " 不存在或获取表信息失败");
                return;
            }
            
            // 生成实体类
            generateEntity(tableInfo);
            
            // 生成DAO接口
            generateDao(tableInfo);
            
            // 生成Mapper XML
            generateMapperXml(tableInfo);
            
            // 生成Service接口
            generateService(tableInfo);
            
            // 生成Service实现类
            generateServiceImpl(tableInfo);
            
            // 生成Controller
            generateController(tableInfo);
            
            System.out.println("代码生成完成！");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取表信息
     */
    private static TableInfo getTableInfo(String tableName) {
        Connection conn = null;
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            
            // 获取表注释
            String tableComment = "";
            String sql = "SELECT TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'snapan' AND TABLE_NAME = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, tableName);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                tableComment = rs.getString("TABLE_COMMENT");
            }
            
            // 获取字段信息
            List<ColumnInfo> columns = new ArrayList<>();
            sql = "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT, COLUMN_KEY " +
                  "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'snapan' AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION";
            ps = conn.prepareStatement(sql);
            ps.setString(1, tableName);
            rs = ps.executeQuery();
            
            while (rs.next()) {
                ColumnInfo column = new ColumnInfo();
                column.setColumnName(rs.getString("COLUMN_NAME"));
                column.setDataType(rs.getString("DATA_TYPE"));
                column.setNullable("YES".equals(rs.getString("IS_NULLABLE")));
                column.setDefaultValue(rs.getString("COLUMN_DEFAULT"));
                column.setComment(rs.getString("COLUMN_COMMENT"));
                column.setPrimaryKey("PRI".equals(rs.getString("COLUMN_KEY")));
                columns.add(column);
            }
            
            TableInfo tableInfo = new TableInfo();
            tableInfo.setTableName(tableName);
            tableInfo.setClassName(toCamelCase(tableName, true));
            tableInfo.setTableComment(tableComment);
            tableInfo.setColumns(columns);
            
            return tableInfo;
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 生成实体类
     */
    private static void generateEntity(TableInfo tableInfo) throws IOException {
        String className = tableInfo.getClassName();
        String filePath = SRC_PATH + "/" + ENTITY_PACKAGE.replace(".", "/") + "/" + className + ".java";
        
        StringBuilder code = new StringBuilder();
        code.append("package ").append(ENTITY_PACKAGE).append(";\n\n");
        code.append("import java.util.Date;\n\n");
        code.append("/**\n");
        code.append(" * ").append(tableInfo.getTableComment()).append("\n");
        code.append(" */\n");
        code.append("public class ").append(className).append(" {\n\n");
        
        // 字段
        for (ColumnInfo column : tableInfo.getColumns()) {
            code.append("    /**\n");
            code.append("     * ").append(column.getComment()).append("\n");
            code.append("     */\n");
            code.append("    private ").append(getJavaType(column.getDataType())).append(" ").append(toCamelCase(column.getColumnName(), false)).append(";\n\n");
        }
        
        // 构造函数
        code.append("    public ").append(className).append("() {}\n\n");
        
        // Getter和Setter方法
        for (ColumnInfo column : tableInfo.getColumns()) {
            String fieldName = toCamelCase(column.getColumnName(), false);
            String methodName = toCamelCase(column.getColumnName(), true);
            String javaType = getJavaType(column.getDataType());
            
            code.append("    public ").append(javaType).append(" get").append(methodName).append("() {\n");
            code.append("        return ").append(fieldName).append(";\n");
            code.append("    }\n\n");
            
            code.append("    public void set").append(methodName).append("(").append(javaType).append(" ").append(fieldName).append(") {\n");
            code.append("        this.").append(fieldName).append(" = ").append(fieldName).append(";\n");
            code.append("    }\n\n");
        }
        
        code.append("}\n");
        
        writeFile(filePath, code.toString());
        System.out.println("生成实体类: " + filePath);
    }
    
    /**
     * 生成DAO接口
     */
    private static void generateDao(TableInfo tableInfo) throws IOException {
        String className = tableInfo.getClassName();
        String filePath = SRC_PATH + "/" + DAO_PACKAGE.replace(".", "/") + "/" + className + "Dao.java";
        
        StringBuilder code = new StringBuilder();
        code.append("package ").append(DAO_PACKAGE).append(";\n\n");
        code.append("import ").append(ENTITY_PACKAGE).append(".").append(className).append(";\n");
        code.append("import org.apache.ibatis.annotations.Param;\n\n");
        code.append("import java.util.List;\n\n");
        code.append("/**\n");
        code.append(" * ").append(tableInfo.getTableComment()).append("数据访问接口\n");
        code.append(" */\n");
        code.append("public interface ").append(className).append("Dao {\n\n");
        
        // 基本CRUD方法
        code.append("    /**\n");
        code.append("     * 根据ID查询\n");
        code.append("     */\n");
        code.append("    ").append(className).append(" selectById(Long id);\n\n");
        
        code.append("    /**\n");
        code.append("     * 查询所有\n");
        code.append("     */\n");
        code.append("    List<").append(className).append("> selectAll();\n\n");
        
        code.append("    /**\n");
        code.append("     * 插入\n");
        code.append("     */\n");
        code.append("    int insert(").append(className).append(" ").append(toCamelCase(className, false)).append(");\n\n");
        
        code.append("    /**\n");
        code.append("     * 更新\n");
        code.append("     */\n");
        code.append("    int update(").append(className).append(" ").append(toCamelCase(className, false)).append(");\n\n");
        
        code.append("    /**\n");
        code.append("     * 根据ID删除\n");
        code.append("     */\n");
        code.append("    int deleteById(Long id);\n\n");
        
        code.append("}\n");
        
        writeFile(filePath, code.toString());
        System.out.println("生成DAO接口: " + filePath);
    }
    
    /**
     * 生成Mapper XML
     */
    private static void generateMapperXml(TableInfo tableInfo) throws IOException {
        String className = tableInfo.getClassName();
        String filePath = PROJECT_PATH + "/src/main/resources/mapper/" + className + "Mapper.xml";
        
        StringBuilder code = new StringBuilder();
        code.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        code.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \n");
        code.append("\"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
        code.append("<mapper namespace=\"").append(DAO_PACKAGE).append(".").append(className).append("Dao\">\n\n");
        
        // 结果映射
        code.append("    <!-- 结果映射 -->\n");
        code.append("    <resultMap id=\"BaseResultMap\" type=\"").append(ENTITY_PACKAGE).append(".").append(className).append("\">\n");
        for (ColumnInfo column : tableInfo.getColumns()) {
            if (column.isPrimaryKey()) {
                code.append("        <id column=\"").append(column.getColumnName()).append("\" property=\"").append(toCamelCase(column.getColumnName(), false)).append("\" jdbcType=\"").append(getJdbcType(column.getDataType())).append("\"/>\n");
            } else {
                code.append("        <result column=\"").append(column.getColumnName()).append("\" property=\"").append(toCamelCase(column.getColumnName(), false)).append("\" jdbcType=\"").append(getJdbcType(column.getDataType())).append("\"/>\n");
            }
        }
        code.append("    </resultMap>\n\n");
        
        // 基础字段
        code.append("    <!-- 基础字段 -->\n");
        code.append("    <sql id=\"Base_Column_List\">\n");
        code.append("        ");
        for (int i = 0; i < tableInfo.getColumns().size(); i++) {
            if (i > 0) code.append(", ");
            code.append(tableInfo.getColumns().get(i).getColumnName());
        }
        code.append("\n");
        code.append("    </sql>\n\n");
        
        // 基本SQL语句
        code.append("    <!-- 根据ID查询 -->\n");
        code.append("    <select id=\"selectById\" parameterType=\"java.lang.Long\" resultMap=\"BaseResultMap\">\n");
        code.append("        SELECT <include refid=\"Base_Column_List\"/>\n");
        code.append("        FROM ").append(tableInfo.getTableName()).append("\n");
        code.append("        WHERE id = #{id}\n");
        code.append("    </select>\n\n");
        
        code.append("    <!-- 查询所有 -->\n");
        code.append("    <select id=\"selectAll\" resultMap=\"BaseResultMap\">\n");
        code.append("        SELECT <include refid=\"Base_Column_List\"/>\n");
        code.append("        FROM ").append(tableInfo.getTableName()).append("\n");
        code.append("    </select>\n\n");
        
        code.append("    <!-- 插入 -->\n");
        code.append("    <insert id=\"insert\" parameterType=\"").append(ENTITY_PACKAGE).append(".").append(className).append("\" useGeneratedKeys=\"true\" keyProperty=\"id\">\n");
        code.append("        INSERT INTO ").append(tableInfo.getTableName()).append(" (\n");
        code.append("            ");
        for (int i = 0; i < tableInfo.getColumns().size(); i++) {
            if (i > 0) code.append(", ");
            code.append(tableInfo.getColumns().get(i).getColumnName());
        }
        code.append("\n");
        code.append("        ) VALUES (\n");
        code.append("            ");
        for (int i = 0; i < tableInfo.getColumns().size(); i++) {
            if (i > 0) code.append(", ");
            code.append("#{").append(toCamelCase(tableInfo.getColumns().get(i).getColumnName(), false)).append("}");
        }
        code.append("\n");
        code.append("        )\n");
        code.append("    </insert>\n\n");
        
        code.append("    <!-- 更新 -->\n");
        code.append("    <update id=\"update\" parameterType=\"").append(ENTITY_PACKAGE).append(".").append(className).append("\">\n");
        code.append("        UPDATE ").append(tableInfo.getTableName()).append("\n");
        code.append("        SET ");
        for (int i = 0; i < tableInfo.getColumns().size(); i++) {
            ColumnInfo column = tableInfo.getColumns().get(i);
            if (column.isPrimaryKey()) continue;
            if (i > 0 && !tableInfo.getColumns().get(i-1).isPrimaryKey()) code.append(", ");
            code.append(column.getColumnName()).append(" = #{").append(toCamelCase(column.getColumnName(), false)).append("}");
        }
        code.append("\n");
        code.append("        WHERE id = #{id}\n");
        code.append("    </update>\n\n");
        
        code.append("    <!-- 根据ID删除 -->\n");
        code.append("    <delete id=\"deleteById\" parameterType=\"java.lang.Long\">\n");
        code.append("        DELETE FROM ").append(tableInfo.getTableName()).append(" WHERE id = #{id}\n");
        code.append("    </delete>\n\n");
        
        code.append("</mapper>");
        
        writeFile(filePath, code.toString());
        System.out.println("生成Mapper XML: " + filePath);
    }
    
    /**
     * 生成Service接口
     */
    private static void generateService(TableInfo tableInfo) throws IOException {
        String className = tableInfo.getClassName();
        String filePath = SRC_PATH + "/" + SERVICE_PACKAGE.replace(".", "/") + "/" + className + "Service.java";
        
        StringBuilder code = new StringBuilder();
        code.append("package ").append(SERVICE_PACKAGE).append(";\n\n");
        code.append("import ").append(ENTITY_PACKAGE).append(".").append(className).append(";\n\n");
        code.append("import java.util.List;\n\n");
        code.append("/**\n");
        code.append(" * ").append(tableInfo.getTableComment()).append("服务接口\n");
        code.append(" */\n");
        code.append("public interface ").append(className).append("Service {\n\n");
        
        // 基本服务方法
        code.append("    /**\n");
        code.append("     * 根据ID查询\n");
        code.append("     */\n");
        code.append("    ").append(className).append(" getById(Long id);\n\n");
        
        code.append("    /**\n");
        code.append("     * 查询所有\n");
        code.append("     */\n");
        code.append("    List<").append(className).append("> getAll();\n\n");
        
        code.append("    /**\n");
        code.append("     * 添加\n");
        code.append("     */\n");
        code.append("    boolean add(").append(className).append(" ").append(toCamelCase(className, false)).append(");\n\n");
        
        code.append("    /**\n");
        code.append("     * 更新\n");
        code.append("     */\n");
        code.append("    boolean update(").append(className).append(" ").append(toCamelCase(className, false)).append(");\n\n");
        
        code.append("    /**\n");
        code.append("     * 删除\n");
        code.append("     */\n");
        code.append("    boolean delete(Long id);\n\n");
        
        code.append("}\n");
        
        writeFile(filePath, code.toString());
        System.out.println("生成Service接口: " + filePath);
    }
    
    /**
     * 生成Service实现类
     */
    private static void generateServiceImpl(TableInfo tableInfo) throws IOException {
        String className = tableInfo.getClassName();
        String filePath = SRC_PATH + "/" + SERVICE_PACKAGE.replace(".", "/") + "/impl/" + className + "ServiceImpl.java";
        
        StringBuilder code = new StringBuilder();
        code.append("package ").append(SERVICE_PACKAGE).append(".impl;\n\n");
        code.append("import ").append(DAO_PACKAGE).append(".").append(className).append("Dao;\n");
        code.append("import ").append(ENTITY_PACKAGE).append(".").append(className).append(";\n");
        code.append("import ").append(SERVICE_PACKAGE).append(".").append(className).append("Service;\n");
        code.append("import org.springframework.beans.factory.annotation.Autowired;\n");
        code.append("import org.springframework.stereotype.Service;\n");
        code.append("import org.springframework.transaction.annotation.Transactional;\n\n");
        code.append("import java.util.List;\n\n");
        code.append("/**\n");
        code.append(" * ").append(tableInfo.getTableComment()).append("服务实现类\n");
        code.append(" */\n");
        code.append("@Service\n");
        code.append("@Transactional\n");
        code.append("public class ").append(className).append("ServiceImpl implements ").append(className).append("Service {\n\n");
        
        code.append("    @Autowired\n");
        code.append("    private ").append(className).append("Dao ").append(toCamelCase(className, false)).append("Dao;\n\n");
        
        // 实现方法
        code.append("    @Override\n");
        code.append("    public ").append(className).append(" getById(Long id) {\n");
        code.append("        return ").append(toCamelCase(className, false)).append("Dao.selectById(id);\n");
        code.append("    }\n\n");
        
        code.append("    @Override\n");
        code.append("    public List<").append(className).append("> getAll() {\n");
        code.append("        return ").append(toCamelCase(className, false)).append("Dao.selectAll();\n");
        code.append("    }\n\n");
        
        code.append("    @Override\n");
        code.append("    public boolean add(").append(className).append(" ").append(toCamelCase(className, false)).append(") {\n");
        code.append("        return ").append(toCamelCase(className, false)).append("Dao.insert(").append(toCamelCase(className, false)).append(") > 0;\n");
        code.append("    }\n\n");
        
        code.append("    @Override\n");
        code.append("    public boolean update(").append(className).append(" ").append(toCamelCase(className, false)).append(") {\n");
        code.append("        return ").append(toCamelCase(className, false)).append("Dao.update(").append(toCamelCase(className, false)).append(") > 0;\n");
        code.append("    }\n\n");
        
        code.append("    @Override\n");
        code.append("    public boolean delete(Long id) {\n");
        code.append("        return ").append(toCamelCase(className, false)).append("Dao.deleteById(id) > 0;\n");
        code.append("    }\n\n");
        
        code.append("}\n");
        
        writeFile(filePath, code.toString());
        System.out.println("生成Service实现类: " + filePath);
    }
    
    /**
     * 生成Controller
     */
    private static void generateController(TableInfo tableInfo) throws IOException {
        String className = tableInfo.getClassName();
        String filePath = SRC_PATH + "/" + CONTROLLER_PACKAGE.replace(".", "/") + "/" + className + "Controller.java";
        
        StringBuilder code = new StringBuilder();
        code.append("package ").append(CONTROLLER_PACKAGE).append(";\n\n");
        code.append("import ").append(ENTITY_PACKAGE).append(".").append(className).append(";\n");
        code.append("import ").append(SERVICE_PACKAGE).append(".").append(className).append("Service;\n");
        code.append("import org.springframework.beans.factory.annotation.Autowired;\n");
        code.append("import org.springframework.web.bind.annotation.*;\n\n");
        code.append("import java.util.HashMap;\n");
        code.append("import java.util.List;\n");
        code.append("import java.util.Map;\n\n");
        code.append("/**\n");
        code.append(" * ").append(tableInfo.getTableComment()).append("控制器\n");
        code.append(" */\n");
        code.append("@RestController\n");
        code.append("@RequestMapping(\"/api/").append(toCamelCase(className, false)).append("\")\n");
        code.append("public class ").append(className).append("Controller {\n\n");
        
        code.append("    @Autowired\n");
        code.append("    private ").append(className).append("Service ").append(toCamelCase(className, false)).append("Service;\n\n");
        
        // 基本CRUD接口
        code.append("    /**\n");
        code.append("     * 获取列表\n");
        code.append("     */\n");
        code.append("    @GetMapping(\"/list\")\n");
        code.append("    public Map<String, Object> getList() {\n");
        code.append("        Map<String, Object> result = new HashMap<>();\n");
        code.append("        try {\n");
        code.append("            List<").append(className).append("> list = ").append(toCamelCase(className, false)).append("Service.getAll();\n");
        code.append("            result.put(\"success\", true);\n");
        code.append("            result.put(\"data\", list);\n");
        code.append("            result.put(\"message\", \"获取列表成功\");\n");
        code.append("        } catch (Exception e) {\n");
        code.append("            result.put(\"success\", false);\n");
        code.append("            result.put(\"message\", \"获取列表失败：\" + e.getMessage());\n");
        code.append("        }\n");
        code.append("        return result;\n");
        code.append("    }\n\n");
        
        code.append("    /**\n");
        code.append("     * 根据ID获取\n");
        code.append("     */\n");
        code.append("    @GetMapping(\"/{id}\")\n");
        code.append("    public Map<String, Object> getById(@PathVariable Long id) {\n");
        code.append("        Map<String, Object> result = new HashMap<>();\n");
        code.append("        try {\n");
        code.append("            ").append(className).append(" ").append(toCamelCase(className, false)).append(" = ").append(toCamelCase(className, false)).append("Service.getById(id);\n");
        code.append("            if (").append(toCamelCase(className, false)).append(" != null) {\n");
        code.append("                result.put(\"success\", true);\n");
        code.append("                result.put(\"data\", ").append(toCamelCase(className, false)).append(");\n");
        code.append("                result.put(\"message\", \"获取成功\");\n");
        code.append("            } else {\n");
        code.append("                result.put(\"success\", false);\n");
        code.append("                result.put(\"message\", \"数据不存在\");\n");
        code.append("            }\n");
        code.append("        } catch (Exception e) {\n");
        code.append("            result.put(\"success\", false);\n");
        code.append("            result.put(\"message\", \"获取失败：\" + e.getMessage());\n");
        code.append("        }\n");
        code.append("        return result;\n");
        code.append("    }\n\n");
        
        code.append("    /**\n");
        code.append("     * 添加\n");
        code.append("     */\n");
        code.append("    @PostMapping(\"/add\")\n");
        code.append("    public Map<String, Object> add(@RequestBody ").append(className).append(" ").append(toCamelCase(className, false)).append(") {\n");
        code.append("        Map<String, Object> result = new HashMap<>();\n");
        code.append("        try {\n");
        code.append("            boolean success = ").append(toCamelCase(className, false)).append("Service.add(").append(toCamelCase(className, false)).append(");\n");
        code.append("            result.put(\"success\", success);\n");
        code.append("            result.put(\"message\", success ? \"添加成功\" : \"添加失败\");\n");
        code.append("        } catch (Exception e) {\n");
        code.append("            result.put(\"success\", false);\n");
        code.append("            result.put(\"message\", \"添加失败：\" + e.getMessage());\n");
        code.append("        }\n");
        code.append("        return result;\n");
        code.append("    }\n\n");
        
        code.append("    /**\n");
        code.append("     * 更新\n");
        code.append("     */\n");
        code.append("    @PutMapping(\"/update\")\n");
        code.append("    public Map<String, Object> update(@RequestBody ").append(className).append(" ").append(toCamelCase(className, false)).append(") {\n");
        code.append("        Map<String, Object> result = new HashMap<>();\n");
        code.append("        try {\n");
        code.append("            boolean success = ").append(toCamelCase(className, false)).append("Service.update(").append(toCamelCase(className, false)).append(");\n");
        code.append("            result.put(\"success\", success);\n");
        code.append("            result.put(\"message\", success ? \"更新成功\" : \"更新失败\");\n");
        code.append("        } catch (Exception e) {\n");
        code.append("            result.put(\"success\", false);\n");
        code.append("            result.put(\"message\", \"更新失败：\" + e.getMessage());\n");
        code.append("        }\n");
        code.append("        return result;\n");
        code.append("    }\n\n");
        
        code.append("    /**\n");
        code.append("     * 删除\n");
        code.append("     */\n");
        code.append("    @DeleteMapping(\"/{id}\")\n");
        code.append("    public Map<String, Object> delete(@PathVariable Long id) {\n");
        code.append("        Map<String, Object> result = new HashMap<>();\n");
        code.append("        try {\n");
        code.append("            boolean success = ").append(toCamelCase(className, false)).append("Service.delete(id);\n");
        code.append("            result.put(\"success\", success);\n");
        code.append("            result.put(\"message\", success ? \"删除成功\" : \"删除失败\");\n");
        code.append("        } catch (Exception e) {\n");
        code.append("            result.put(\"success\", false);\n");
        code.append("            result.put(\"message\", \"删除失败：\" + e.getMessage());\n");
        code.append("        }\n");
        code.append("        return result;\n");
        code.append("    }\n\n");
        
        code.append("}\n");
        
        writeFile(filePath, code.toString());
        System.out.println("生成Controller: " + filePath);
    }
    
    /**
     * 写入文件
     */
    private static void writeFile(String filePath, String content) throws IOException {
        File file = new File(filePath);
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
        
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(content);
        }
    }
    
    /**
     * 转换为驼峰命名
     */
    private static String toCamelCase(String str, boolean capitalizeFirst) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        
        StringBuilder result = new StringBuilder();
        boolean nextUpper = capitalizeFirst;
        
        for (char c : str.toCharArray()) {
            if (c == '_') {
                nextUpper = true;
            } else {
                if (nextUpper) {
                    result.append(Character.toUpperCase(c));
                    nextUpper = false;
                } else {
                    result.append(Character.toLowerCase(c));
                }
            }
        }
        
        return result.toString();
    }
    
    /**
     * 获取Java类型
     */
    private static String getJavaType(String dbType) {
        if (dbType == null) return "String";
        
        switch (dbType.toLowerCase()) {
            case "bigint":
                return "Long";
            case "int":
            case "integer":
                return "Integer";
            case "smallint":
                return "Short";
            case "tinyint":
                return "Byte";
            case "decimal":
            case "numeric":
            case "float":
            case "double":
                return "Double";
            case "datetime":
            case "timestamp":
                return "Date";
            case "date":
                return "Date";
            case "text":
            case "longtext":
            case "mediumtext":
            case "varchar":
            case "char":
            default:
                return "String";
        }
    }
    
    /**
     * 获取JDBC类型
     */
    private static String getJdbcType(String dbType) {
        if (dbType == null) return "VARCHAR";
        
        switch (dbType.toLowerCase()) {
            case "bigint":
                return "BIGINT";
            case "int":
            case "integer":
                return "INTEGER";
            case "smallint":
                return "SMALLINT";
            case "tinyint":
                return "TINYINT";
            case "decimal":
            case "numeric":
                return "DECIMAL";
            case "float":
                return "FLOAT";
            case "double":
                return "DOUBLE";
            case "datetime":
            case "timestamp":
                return "TIMESTAMP";
            case "date":
                return "DATE";
            case "text":
            case "longtext":
            case "mediumtext":
                return "LONGVARCHAR";
            case "varchar":
                return "VARCHAR";
            case "char":
                return "CHAR";
            default:
                return "VARCHAR";
        }
    }
    
    /**
     * 表信息类
     */
    public static class TableInfo {
        private String tableName;
        private String className;
        private String tableComment;
        private List<ColumnInfo> columns;
        
        // getter和setter方法
        public String getTableName() { return tableName; }
        public void setTableName(String tableName) { this.tableName = tableName; }
        public String getClassName() { return className; }
        public void setClassName(String className) { this.className = className; }
        public String getTableComment() { return tableComment; }
        public void setTableComment(String tableComment) { this.tableComment = tableComment; }
        public List<ColumnInfo> getColumns() { return columns; }
        public void setColumns(List<ColumnInfo> columns) { this.columns = columns; }
    }
    
    /**
     * 字段信息类
     */
    public static class ColumnInfo {
        private String columnName;
        private String dataType;
        private boolean nullable;
        private String defaultValue;
        private String comment;
        private boolean primaryKey;
        
        // getter和setter方法
        public String getColumnName() { return columnName; }
        public void setColumnName(String columnName) { this.columnName = columnName; }
        public String getDataType() { return dataType; }
        public void setDataType(String dataType) { this.dataType = dataType; }
        public boolean isNullable() { return nullable; }
        public void setNullable(boolean nullable) { this.nullable = nullable; }
        public String getDefaultValue() { return defaultValue; }
        public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; }
        public String getComment() { return comment; }
        public void setComment(String comment) { this.comment = comment; }
        public boolean isPrimaryKey() { return primaryKey; }
        public void setPrimaryKey(boolean primaryKey) { this.primaryKey = primaryKey; }
    }
    
    /**
     * 主方法，用于测试
     */
    public static void main(String[] args) {
        // 生成用户表的代码
        generateCode("file_chunk");
        
        // 可以继续生成其他表的代码
        // generateCode("product");
        // generateCode("order");
    }
}


